package cn.itcast.store.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.store.domain.Cart;
import cn.itcast.store.domain.Cartlterm;
import cn.itcast.store.domain.Product;
import cn.itcast.store.service.ProductService;
import cn.itcast.store.service.serviceImp.ProductServiceImp;
import cn.itcast.store.web.base.BaseServlet;

/**
 * Servlet implementation class CartServlet
 */
public class CartServlet extends BaseServlet {
	
	public String removeCartItem(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		String pid = request.getParameter("id");
		Cart cart=(Cart)request.getSession().getAttribute("Cart");
		
		cart.removeCartItem(pid);
		response.sendRedirect("/shopping/jsp/cart.jsp");
		return null;
	}
	
	
	
	public String emptyCart(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		Cart cart=(Cart)request.getSession().getAttribute("Cart");
		cart.clearCart();
		response.sendRedirect("/shopping/jsp/cart.jsp");
		return null;
	}
	

	
	public String addToCart(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException, SQLException {
		try {
			
			Cart cart = (Cart) request.getSession().getAttribute("Cart");
			if (null == cart) {
				cart = new Cart();
				request.getSession().setAttribute("Cart", cart);
			}
			// System.out.println(cart);
			// System.out.println("11111111111111111111");

			int num = Integer.parseInt(request.getParameter("num"));

			// System.out.println("12111111111111");
			String pid = request.getParameter("pid");
			// System.out.println("2qwwwwwwwwww");

			
			ProductService ProductService = new ProductServiceImp();

			Product Product = ProductService.findProductByPid(pid);
			System.out.println(Product);
			Cartlterm Cartlterm = new Cartlterm();
			Cartlterm.setNum(num);
			Cartlterm.setProduct(Product);
			
			System.out.println(pid);
			
			
			cart.addCartItemToCar(Cartlterm);
			
			
			//System.out.println(cart);
			// return "/jsp/cart.jsp";
			response.sendRedirect("/shopping/jsp/cart.jsp");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

		return null;
	}

}
